import json
from random import randrange

from django.http import HttpResponse
from rest_framework.views import APIView
from django.shortcuts import render,redirect,reverse
from django.views.generic import View
from pyecharts.charts import Bar
from pyecharts import options as opts

from apps.wx_offical_account.models import WxOfficalAccount
from django.db.models import Max,Min,Sum,Count,Avg
# Create your views here.
def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    data.update(kwargs)
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error


def bar_base() -> Bar:
    all_num = list()
    kyk_nums = list()
    hk_nums = list()
    # 获取所有分类
    type_tag_list = WxOfficalAccount.objects.filter(is_delete=0).values_list("article_type",flat=True).distinct()
    # 统计每个公众号的数据量  分组求和


    kyk = WxOfficalAccount.objects.filter(user_for=1).values_list('article_type').annotate(Count('id'))
    hk = WxOfficalAccount.objects.filter(user_for=1).values_list('article_type').annotate(Count('id'))
    for i in kyk:
        kyk_nums.append(i[1])
    for i in hk:
        hk_nums.append(i[1])
    # kyk_nums.append(i[1] for i in kyk)
    # hk_nums.append(i[1] for i in hk)

    alls = WxOfficalAccount.objects.values_list('article_type').annotate(Count('id'))
    for i in alls:
        all_num.append(i[1])
    c = (
        Bar()
        .add_xaxis(list(type_tag_list))
        .add_yaxis("官网", kyk_nums)
        .add_yaxis("51客", hk_nums)
        .add_yaxis("全部", all_num)
        .set_global_opts(title_opts=opts.TitleOpts(title="公众号数量", subtitle="公众号总数:{sum}".format(sum=WxOfficalAccount.objects.count())))
        .dump_options_with_quotes()
    )
    return c


class ChartView(APIView):
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base()))


class showView(View):
    def get(self, request):
        return render(request,'official_data.html')